<!DOCTYPE HTML>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="maximum-scale=1.0, minimum-scale=1.0, user-scalable=0, initial-scale=1.0, width=device-width"/>
    <meta name="format-detection" content="telephone=no, email=no, date=no, address=no">
    <title>首页</title>
    <link rel="stylesheet" type="text/css" href="../../css/api.css" />
    <link rel="stylesheet" type="text/css" href="../../css/main.css" />
    <link rel="stylesheet" type="text/css" href="../../css/demo/article.css" />
</head>
<body>
  <div id="header">
    <div id="back"></div>
      <h3>帖子详情</h3>
  </div>
<div id="all">
  <div class="content_title">
      <h4></h4>
  </div>
  <div class="content">
  </div>
  <div class="attention"><span>关注</span><span>取消关注</span><span class="top">置顶</span><span class="normal">取消置顶</span></div>
  <h3 class="partingline">精彩评论</h3>
  <div class="bt">
  </div>

</div>
</body>
<script type="text/javascript" src="../../script/jquery.js"></script>
<script type="text/javascript" src="../../script/api.js"></script>
<script type="text/javascript" src="../../script/main.js"></script>
<script type="text/javascript">
apiready=function(){
var emotionData;
  //获取all 这个div的对象
var scrollAll_Div = document.getElementById("all");
//获取评论的page
var count=0;
//接收job.html页面传过来的参数
var publicMsgId=api.pageParam.id; //文章的id
//用于getComment(x,x,x)方法里面判断是否进行置底操作
var faker=false;
//获取登陆人ID
var aid=$api.getStorage("aid");
var flag=$api.getStorage("flag");
var userHeaderImageUrl=$api.getStorage("userHeaderImageUrl");
var userName=$api.getStorage("nickname");

init();
//--------------------------------------------------------------------------------------------------
var UIChatBox = api.require('UIChatBox');
$(".bt").on("click",".reply",function(){
  //UIChatBox.popupKeyboard();
  if(aid== $(this).attr('commentsAid-id')){
      alert("不能回复自己！");
  }else{
    UIChatBox.insertValue({
      index: 0,
      msg:'@'+$(this).attr('commentsAid-name')
    });
  }
});
//--------------------------------------------------------------------------------------------------
  UIChatBox.open({
  placeholder: '请输入评论...',
  emotionPath: 'widget://image/emotion',
  maxRows: 4,
  texts: {
      sendBtn: {
          title: 'send'
      }
  },
  styles: {
      inputBar: {
          borderColor: '#d9d9d9',
          bgColor: '#f2f2f2'
      },
      emotionBtn: {
          normalImg: 'widget://image/face.png'
      },
      inputBox: {
          borderColor: '#B3B3B3',
          bgColor: '#FFFFFF'
      },
      sendBtn: {
          titleColor: '#4cc518',
          bg: '#999999',
          activeBg: '#46a91e',
          titleSize: 14
      }
  }
}, function(ret, err) {
  if(ret.eventType=="send"){
    if(ret.msg){
      issueComment(ret.msg);
    }else{
      toast("不能发布空评论","middle");
    }

  }
});
//-----------------------------------------------------------------------------------------------
//初始化操作根据id获取文章
function init(){
  var msgUrl="/api/public-msgs/"+publicMsgId;
  var functionRet=function(ret1){
    if(ret1){
        $(".content").append('<div class="font"><span type='+ret1.type+' topLevel='+ret1.topLevel+'>'+ret1.content+'</span></div><div class="Image"></div>');
        var imageSrc=ret1.imageList.toString().split(',')
        for(var i=0;i<imageSrc.length;i++){
          //imageSrc[i].replace(/["'"]/g代表将全局的"''"全部替换成空字符串，即去掉获取到的字符串两边的引号
          var imgs='<img src='+"http://"+imageSrc[i].replace(/["'"]/g,"")+'>';
          $(".Image").append(imgs);
        }

        var h4= $(".content_title h4");
        var title = ret1.title;
        // if(title.length>6){
        //   title = title.substring(0,6)+"..."
        // }
        h4.html(title);
        isTop();
      }
  }
  var functionErr=function(err1){
    if(err1.statusCode==404){
        alert("文章不存在！");
        //api.closeWin();
      }
    }
  get(msgUrl,functionRet,functionErr);
  getComment(count,10,faker);
}
function isTop(){
  //判断是否为当前文章的版主
  var url="/api/moderator-applies/moderatorType?aid="+aid;
  var functionRet=function(ret){

  }
  var functionErr=function(err){
      if(err.body==$(".font span").attr("type")){
        if($(".font span").attr("topLevel")==0){
          //未置顶的
           $(".top").show();
        }else{
          //置顶过的
           $(".normal").show();
        }
      }
    }
  get(url,functionRet,functionErr);
}
//----------------------------------------------------------------------------------------------
//创建评论
function issueComment (msg){
  var msgUrl="/api/public-msg-comments";
  var data={
  "aid": aid,
  "content": msg,
  "publicMsgId": publicMsgId
  }
  var functionRet=function(ret1){
  if(count<0){
    count=0;
  }

        //将评论显示在页面上
    //置底操作
    faker=true;
    //getComment(0,10,faker);
    $(".bt").html("");
    getComment(0,10*(count+1),faker);
    UIChatBox.closeKeyboard();
    //scroll_top();
  }
  var functionErr=function(err1){
    return false;
  }
  post(msgUrl,data,functionRet,functionErr);
}
//----------------------------------------------------------------------------------
//刪除評論
function deleteContent(id){
    //var msgUrl="/api/public-msg-comments/{id}?path="+id;
    var data="";
    var msgUrl="/api/public-msg-comments/"+id;
    var functionRet=function(ret1){
    }
    var functionErr=function(err1){
      if(err1.statusCode==200){
        //将点击删除按钮时的滚动条高度记下
        var height=scrollAll_Div.scrollTop;
        alert("评论删除成功！");
        //window.location.reload();
        $(".bt").html("");
        getComment(0,10*(count+1),faker);
        //删除评论后评论区会置顶
        //所以将之前记下的高度赋值给滚动条，让它返回之前的高度
        //scrollAll_Div.scrollTop=height;
      }
    }
    deleteData(msgUrl,data,functionRet,functionErr);
}
//----------------------------------------------------------------------------------------------
//获取评论
function getComment(page,size,faker){

  var msgUrl="/api/public-msg-comments?publicMsgId="+publicMsgId+"&page="+page+"&size="+size;
  var functionRet=function(ret1){
    if(ret1.length){
      for (var i = 0; i < ret1.length; i++) {
        var talk_content=transText(ret1[i].publicMsgComment.content);
        var userHeaderImageUrl=ret1[i].userHeaderImageUrl;
        if(ret1[i].userHeaderImageUrl=='#'){
          userHeaderImageUrl='../../image/personal_head.png';
        }
        $(".bt").append('<div class="comment"><div class="reply_c"><img src='+userHeaderImageUrl+'><span class="commentName">'+ret1[i].userName+'</span></div><div class="commentFont"><span>'+talk_content+'</span></div><span class="reply" commentsAid-id='+ret1[i].publicMsgComment.aid+' commentsAid-name='+ret1[i].userName+'>回复</span><span class="delete" comment-id='+ret1[i].publicMsgComment.id+' commentsAid-id='+ret1[i].publicMsgComment.aid+'>删除</span><div class="ct"></div></div>');
        // if(ret1[i].publicMsgComment.aid!=aid){
        //   $(".delete").css("display","none");
        // }
        // if(ret1[i].publicMsgComment.aid==aid){
        //   $(".reply").css("display","none");
        // }
      }
      if(faker){
        scroll_top();
        faker=false;
      }
    }else{
      count--;
    }
  }


  var functionErr=function(err1){
    if(err1.statusCode==200){
          return true;
      }
  }
  getU(msgUrl,functionRet,functionErr);
}
//--------------------------------------------------------------------------------------
//监听输入框所在区域弹动事件
// var UIChatBox = api.require('UIChatBox');
// UIChatBox.addEventListener({
//     target: 'inputBar',
//     name: 'move'
// }, function(ret, err) {
//       if(ret.panelHeight>100){
//         //scroll_top();
//       //当点击输入框时 ，聊天框定位想上弹起
//         var _h=ret.panelHeight+"px";
//         //判断系统类型
//         //  var systemType = api.systemType;
//         //if(systemType=='android'){
//         //安卓
//         //  $("#all").css("bottom",40);
//         //}else{
//         //ios
//         scrollAll_Div.style.bottom=_h;
//         scrollAll_Div.style.top=ret.panelHeight*(-1)+'px';
//         //}
//     }else{
//         scrollAll_Div.style.bottom=0;
//         scrollAll_Div.style.top='60px';
//     }

// });
//--------------------------------------------------------------------------------------
//表情转换
function transText(text, imgWidth, imgHeight){
    var imgWidth = imgWidth || 30;
    var imgHeight = imgHeight || 30;
    var regx = /\[(.*?)\]/gm;
    var textTransed = text.replace(regx,function(match){
        var imgSrc = emotionData[match];
        if(!imgSrc){
                //说明不对应任何表情，直接返回
                return match;
        }
        var img = "<img src="+imgSrc+" width="+imgWidth+" height="+imgHeight+">";
        return img;
    });
    return textTransed;
}
var sourcePath = "widget://image/emotion";//表情存放目录
getImgsPaths(sourcePath, function (emotion) {
      emotionData = emotion;
});
function getImgsPaths(sourcePathOfChatBox, callback){
var jsonPath = "widget://image/emotion/emotion.json";//表情的JSON数组
api.readFile({
    path: jsonPath
    },function(ret,err){
        if(ret.status){
            var emotionArray = JSON.parse(ret.data);
            var emotion = {};
            for(var idx in emotionArray){
                    var emotionItem = emotionArray[idx];
                    var emotionText = emotionItem["text"];
                    var emotionUrl = "../../image/emotion/"+emotionItem["name"]+".png";
                    emotion[emotionText] = emotionUrl;
            }
            /*把emotion对象 回调出去*/
            if("function" === typeof(callback)){
                    callback(emotion);
            }
        }
    });
}
//---------------------------------------------------------------------------------------------
//当滚动条置底时加载数据
//每10条加载一次数据
 $("#all").scroll(function(){
 var viewH =$(this).height();//可见高度
 var contentH =$(this).get(0).scrollHeight;//内容高度
 var scrollTop =$(this).scrollTop();//滚动高度
 //console.log(scrollTop/(contentH -viewH))
 if(scrollTop/(contentH -viewH)>=1){ //到达底部5%以内,加载新内容
 // 这里加载数据..
 count++;
 // console.log("gg"+count)
getComment(count,10,faker);
 // if(ah==1){
 //  alert("count")
 //   count--;
 // }

 }
 });
  //点击删除按钮
 $(".bt").on("click",".delete",function(){
   if(aid== $(this).attr('commentsAid-id')){
       deleteContent($(this).attr('comment-id'));
   }else if(flag==7){
        deleteContent($(this).attr('comment-id'));
   }else{
        alert("不能删除别人的评论！");
   }
 });

 //版主置顶
 $(".top").click(function(){
   var url='/api/public-msgs/'+publicMsgId+'/topLevel?topLevel=1';
   var data={};
   var functionRet=function(ret){
     alert(JSON.stringify(ret))
   }
   var functionErr=function(err){
     if(err.statusCode==200){
       toast("置顶成功！","middle");
       location.reload();
      //  var jsfun = 'history.go(0);';
      //  api.execScript({
      //      name: 'root',
      //      frameName: 'frame2',
      //      script: jsfun
      //  });
     }
   }
   put(url,data,functionRet,functionErr);
 })
//版主取消置顶
$(".normal").click(function(){
  var url='/api/public-msgs/'+publicMsgId+'/topLevel?topLevel=0';
  var data={};
  var functionRet=function(ret){
    alert(JSON.stringify(ret))
  }
  var functionErr=function(err){
    if(err.statusCode==200){
      toast("取消置顶成功！","middle");
      location.reload();
      // api.execScript({
      //     name: 'root',
      //     frameName: 'frame2',
      //     script: 'history.go(0)'
      // });
    }
  }
  put(url,data,functionRet,functionErr);
})
 //关注和取消关注
 $(".attention span:eq(0)").click(function(){
    var url='/api/public-msgs/'+publicMsgId+'/attentionAid?attentionAid='+aid;
    var data={};
    var functionRet=function(ret){
    }
    var functionErr=function(err){
      if(err.statusCode==200){
        toast("关注成功！","middle");
      }
    }
    postU(url,data,functionRet,functionErr);
 })

 $(".attention span:eq(1)").click(function(){
    var url='/api/public-msgs/'+publicMsgId+'/attentionAid?attentionAid='+aid;
    var data={};
    var functionRet=function(ret){
    }
    var functionErr=function(err){
      if(err.statusCode==200){
        toast("取消关注成功！","middle");
      }
    }
    deleteDataU(url,data,functionRet,functionErr);
 })
 //点击删除按钮
 // $(".bt").on("click",".delete",function(){
 //   if(aid!= $(this).attr('commentsAid-id')){
 //       alert("不能删除别人的评论！");
 //   }else{
 //     deleteContent($(this).attr('comment-id'));
 //   }
 // });
 //---------------------------------------------------------------------------------------------
//将滚动条滚到底部函数
function scroll_top(){
    scrollAll_Div.scrollTop=scrollAll_Div.scrollHeight;
  }

} //apiready=function() 函数的括号
$(function(){
  back();
})
</script>
</html>
